define(function(require, exports, module){
	
	/**
     * @name FormatXML#getHtml
     * @function   
     * @desc 格式化xml文件返回html。
     * @param {Object} xml
     */
	var getHtml = function(xml){
		var tmpl = '';
		if(semi.utils.isEmpty(xml))return '';
		$(xml).each(function(){
			if($(this).isTag('repeat')){
				tmpl += formatRepeat($(this));
			}else if($(this).isTag('line')){
				tmpl += formatLine($(this));
			}else if($(this).isTag('text')){
				tmpl += formatText($(this));
			}else if($(this).isTag('textbox')){
				tmpl += formatTextbox($(this));
			}else if($(this).isTag('select')){
				tmpl += formatSelect($(this));
			}
		});
		//检查重名，删除重复name节点
		var nameArr = [],
			checkLine = function(node){
				node.children().each(function(){
					var name = $(this).attr('name');
					if(semi.utils.isEmpty(name))return true;
					if(nameArr.indexOf(name)==-1){
						nameArr.push(name);
					}else{
						$(this).remove();
					}
				});
			}, 
			_tmpl = '';
		
		$(tmpl).each(function(){
			if($(this).hasClass('alg_line')){
				checkLine($(this));
			}else if($(this).hasClass('alg_repeat')){
				$(this).children().each(function(){
					if($(this).hasClass('alg_line'))checkLine($(this));
				});
			}
			_tmpl += $(this)[0].outerHTML
		});
		return _tmpl;
	}
	var formatRepeat = function(node){
		/*repeat元素的子元素是line
		name代表repeat元素的变量名
		min代表最少多少line
		max代表最大多少line*/
		var tmpl = '',
			name = node.attr('name') || '',
			min = parseInt(node.attr('min')) || 0,
			max = parseInt(node.attr('max')) || 100;
		
		if(semi.utils.isEmpty(name))return '';
		if(node.find('repeat').remove().end().children().size()<1){
			tmpl = node.text();
		}else{
			node.find('repeat').remove().end().children().each(function(){
				if($(this).isTag('line')){
					tmpl += formatLine($(this));
				}else if($(this).isTag('text')){
					tmpl += formatText($(this));
				}else if($(this).isTag('textbox')){
					tmpl += formatTextbox($(this));
				}else if($(this).isTag('select')){
					tmpl += formatSelect($(this));
				}
			});
		}
		if(min>max)min=max;
		return '<div class="alg_repeat" name="'+name+'" '+(min>0?'min="'+min+'"':'')+' max="'+max+'">'+tmpl+'<span class="glyphicon glyphicon-plus alg_plus" title="复制"></span></div>';
	}
	var formatLine = function(node){
		/*模板的核心元素是line，每一个line代表UI上的一行*/
		var tmpl = '';
		if(node.find('line').remove().end().children().size()<1){
			tmpl = node.text();
		}else{
			node.find('line').remove().end().children().each(function(){
				if($(this).isTag('text')){
					tmpl += formatText($(this));
				}else if($(this).isTag('textbox')){
					tmpl += formatTextbox($(this));
				}else if($(this).isTag('select')){
					tmpl += formatSelect($(this));
				}
			});
		}
		return '<div class="alg_line">'+tmpl+'</div>';
	}
	var formatText = function(node){
		/*text元素：代表一段文字
		width: 宽度
		align: left, center, right 对齐方式
		bold: true, false 表示是否粗体*/
		var tmpl = '<label class="alg_label block"></label>',
			text = node.text() || '',
			width = parseInt(node.attr('width')) || 'auto',
			align = node.attr('align') || '',
			bold = node.attr('bold') || 'false';
		
		if(!isNaN(width)){
			tmpl = $(tmpl).css('width',width+'px')[0].outerHTML;
		}
		if(align=='left'){
			tmpl = $(tmpl).addClass('txtl')[0].outerHTML;
		}else if(align=='center'){
			tmpl = $(tmpl).addClass('txtc')[0].outerHTML;
		}else if(align=='right'){
			tmpl = $(tmpl).addClass('txtr')[0].outerHTML;
		}
		if(bold=='true'){
			tmpl = $(tmpl).css('font-weight', 'bold')[0].outerHTML;
		}
		tmpl = $(tmpl).text(text)[0].outerHTML;
		return tmpl;
	}
	var formatTextbox = function(node){
		/*textbox元素：一个文字输入框
		name: 对应的变量名
		width: 宽度
		type: 变量类型。支持 number, string, datetime 3种类型
		default: 默认值，类型必须和type一致*/
		var tmpl = '<input class="form-control alg_ipt block" type="text" name="" value="{value}"/>',
			name = node.attr('name') || '',
			width = parseInt(node.attr('width')) || 130,
			type = node.attr('type') || 'string',
			def = node.attr('default') || '',
			placeholder = node.text() || '请输入';
		
		if(semi.utils.isEmpty(name))return '';
		tmpl = $(tmpl).attr('name', name)[0].outerHTML;
		if(!isNaN(width)){
			tmpl = $(tmpl).css('width',width+'px')[0].outerHTML;
		}
		if(type=='number'){
			tmpl = $(tmpl).addClass('number')[0].outerHTML;
		}else if(type=='datetime'){
			tmpl = $(tmpl).addClass('datetimebox-ipt').attr('readonly','readonly')[0].outerHTML;
			if(semi.utils.isEmpty(placeholder))placeholder = '请选择时间...';
		}else{
			tmpl = $(tmpl).addClass('string')[0].outerHTML;
		}
		if(!semi.utils.isEmpty(def)){
			tmpl = tmpl.replace('{value}', def);
		}else{
			tmpl = tmpl.replace('{value}', '');
		}
		tmpl = $(tmpl).attr('placeholder', placeholder)[0].outerHTML;
		return tmpl;
	}
	var formatSelect = function(node){
		/*select元素：选择输入
		multi: 是否多选
		name: 变量名
		width: 宽度
		type: 变量类型
		default: 默认值。如果是多选，值用逗号分割
		style: 显示的风格。droplist, checkbox, radio*/
		
		var tmpl = '', 
			option = '',
			name = node.attr('name') || '',
			multi = node.attr('multi') || 'false',
			width = parseInt(node.attr('width')) || 'auto',
			def = node.attr('default') || '-1',
			style = node.attr('style') || 'droplist';
		
		if(semi.utils.isEmpty(name))return '';
		if(style=='checkbox'){
			tmpl = '<div class="alg_checkbox block"></div>';
			option = '<label class="checkbox-inline"><input type="checkbox" name="'+name+'" value="{value}"> {text}</label>';
		}else if(style=='radio'){
			tmpl = '<div class="alg_radio block"></div>';
			option = '<label class="radio-inline"><input type="radio" name="'+name+'" value="{value}"> {text}</label>';
		}else{
			tmpl = '<select name="'+name+'" class="select2-ipt txtm block" style="width:130px;" placeholder="请选择..."></select>';
			option = '<option value="{value}">{text}</option>';
			if(multi=='true'){
				tmpl = $(tmpl).attr('multiple','multiple')[0].outerHTML;
			}
		}
		if(!isNaN(width)){
			tmpl = $(tmpl).css('width',width+'px')[0].outerHTML;
		}
		$('option',node).each(function(){
			tmpl = $(tmpl).append(option.replace('{value}', $(this).attr('value')).replace('{text}', $(this).text()))[0].outerHTML;
		});
		if(!semi.utils.isEmpty(def)){
			var _val = def.split(','), _$tmpl = $(tmpl);
			$.each(_val, function(i,n){
				if(style=='checkbox' || style=='radio'){
					_$tmpl.find('[value='+n+']').attr('checked','checked');
				}else{
					_$tmpl.find('[value='+n+']').attr('selected','selected');
				}
			});
			tmpl = _$tmpl[0].outerHTML;
		}
		return tmpl;
	}
	$(document).on('mouseover.alg', '.alg_plus,.alg_minus', function(){
		$(this).parent().css('border-color','#ccc');
	}).on('mouseout.alg', '.alg_plus,.alg_minus', function(){
		$(this).parent().css('border-color','#f6f6f6');
	}).on('click.alg', '.alg_plus', function(){
		if($(this).hasClass('disabled'))return;
		
		var $rpt = $(this).parent(), 
			max = parseInt($rpt.attr('max')) || 'auto',
			children = $rpt.data('children'),
			html = $rpt.data('html'),
			_rpt = $(html).data('mother',$rpt).css('border-color','#f6f6f6').append('<span class="glyphicon glyphicon-minus alg_minus" title="删除"></span>');
		
		$('.alg_plus',_rpt).remove();
		if(semi.utils.isEmpty(children)){
			$rpt.data('children',[]);
			children = $rpt.data('children');
		}
		_rpt.find('input,select').each(function(){
			var _name = $(this).attr('name');
			$(this).attr('name',_name+'_repeat'+children.length);
		});
		if(children.length>0){
			$('.alg_plus',_rpt).remove();
			children[children.length-1].after(_rpt);
		}else{
			$rpt.after(_rpt);
		}
		_rpt.data('index',children.length);
		children.push(_rpt);
		if(children.length+1>=max){
			$(this).addClass('disabled').attr('title','已达上限');
		}else{
			$(this).removeClass('disabled').attr('title','复制');
		}
		_rpt.initUI();
	}).on('click.alg', '.alg_minus', function(){
		if($(this).hasClass('disabled'))return;
		
		var $rpt = $(this).parent(), 
			name = $rpt.attr('name');
			mother = $rpt.data('mother'),
			min = parseInt(mother.attr('min')) || 0,
			index = $rpt.data('index'),
			children = mother.data('children');
		
		$rpt.remove();
		children.splice(index,1);
		mother.siblings('[name='+name+']').each(function(index){
			$(this).data('index',index);
		});
		$('.alg_plus',mother).removeClass('disabled').attr('title','复制');
	});
	
	/**
     * @name FormatXML#getJson
     * @function   
     * @desc 格式化html节点中参数返回json。
     * @param {Object} node
     */
	var getJson = function(node){
		var json = {}, $node = node;
		
		if(typeof node == 'string')$node = $('<div>'+getHtml(node)+'</div>');
		if($('input, select, .alg_line, .alg_repeat',$node).size()<1)return json;
		
		var getParam = function($tag){
				var _json = {},
					_get = function(n, parent){
						var _name = n.attr('name'), _rname = _name, _index = -1;
						
						if(semi.utils.isEmpty(_rname))return;
						 _index = _name.indexOf('_repeat');
						if(_index!=-1)_rname = _name.substr(0,_index);
						if(n.isTag('input') && n.attr('type')=='checkbox'){
							if(semi.utils.isEmpty(_json[_rname])){
								_json[_rname] = [];
							}
							if(n[0].checked)_json[_rname].push(n.val());
							return;
						}
						if(n.isTag('input') && n.attr('type')=='radio'){
							if(semi.utils.isEmpty(_json[_rname])){
								_json[_rname] = '';
							}
							if(n[0].checked)_json[_rname] = n.val();
							return;
						}
						if(n.isTag('select') && n.attr('multiple')=='multiple'){
							if(semi.utils.isEmpty(_json[_rname])){
								_json[_rname] = '';
							}
							var _va = $('[name='+_name+']', (parent || $node)).val();
							if(!semi.utils.isEmpty(_va))_json[_rname] = _va;
							return;
						}
						var _val = $('[name='+_name+']', (parent || $node)).val();
						_json[_rname] = semi.utils.isEmpty(_val)?'':_val;
					}
				
				if($tag.isTag('input') || $tag.isTag('select')){
					_get($tag);
				}else{
					$tag.find('input,select').each(function(){
						_get($(this), $tag);
					});
				}
				return _json;
			}
			
		$node.children().each(function(){
			var $this = $(this);
			if($this.hasClass('alg_repeat')){
				var _name = $this.attr('name');
				if(semi.utils.isEmpty(json[_name])){
					json[_name] = [];
				}
				var _json = {};
				$.extend(_json, getParam($this));
				json[_name].push(_json);
			}else{
				$.extend(json, getParam($this));
			}
		});
		
		return json;
	}
	
	/**
     * @name FormatXML#initJson
     * @function   
     * @desc 使用json填充html节点。
     * @param {Object} node
     */
	var initJson = function(node, json){
		if($('.alg_line, .alg_repeat, input, select',node).size()<1 || semi.utils.isEmpty(json))return;
		
		require.async('parsejson', function($parsejson){
			var _set = function($tag, val){
				/*if($tag.isTag('input') && $tag.attr('type')=='checkbox'){
					if(n.val()==val)n[0].checked=true
					return;
				}*/
				if($tag.isTag('input') && $tag.attr('type')=='radio'){
					$tag.each(function(){
						if($(this).val()==val)$(this)[0].checked=true;
					});
					return;
				}
				$tag.val(val);
			}
			json = $parsejson(json);
			$.each(json, function(i, n){
				var $target = $('[name='+i+']',node);
				if($target.size()<1)return;
				if(!$target.hasClass('alg_repeat')){
					_set($target, n);
				}else if($.isArray(n) && n.length>0){
					while($target.size()<n.length){
						$target.first().children('.alg_plus').click();
						$target = $('[name='+i+']',node);
					}
					$.each(n, function(j, m){
						$.each(m, function(k, o){
							_set($('[name^='+k+']',$target.eq(j)), o);
						});
					});
				}
			});
		});
	}
	
	/**
     * @name FormatXML#initHtml
     * @function   
     * @desc 初始化html片段。
     */
	var initHtml = function(){
		$('.alg_repeat').each(function(){
			var $this = $(this),
				min = parseInt($this.attr('min')) || 0,
				name = $this.attr('name'),
				init = $this.data('init');
			
			if(semi.utils.isEmpty(name) || (!semi.utils.isEmpty(init) && init) || $('.alg_plus',$this).hasClass('disabled') || isNaN(min))return;
			if(semi.utils.isEmpty($this.data('html'))){
				$this.data('html',$this[0].outerHTML);
			}
			for(var i=1; i<min; i++){
				$('.alg_plus',$this).click();
				$('.alg_repeat[name='+name+']:last').find('.alg_minus').addClass('disabled').attr('title','默认项');
			}
			$this.data('init', true).initUI();
		});
		
		var getH = function(){
			var _arr = [];
			$('.alg_line').each(function(){
				_arr.push($(this).height());
			});
			if(semi.utils.isEmpty(_arr))return 0;
			return _arr.max();
		}
		$('.uicontent').css('width','auto');
		while(getH()>50 && $('.uicontent').width()<2048){$('.uicontent').width($('.uicontent').width()+10)}
	}
	
	/**
     * @name FormatXML#getTemplete
     * @function   
     * @desc 返回模板代码。
     */
	var getTemplete = function(name, type){
		var tmpl = '', random = Math.round(Math.random()*1000000);
		
		if(semi.utils.isEmpty(name))return tmpl;
		if(semi.utils.isEmpty(type))type='';
		switch(name){
			case 'line':
				tmpl = '<line>这是单行</line>';
				break;
			case 'text':
				tmpl = '<text width="" align="left" bold="false">文本标签</text>';
				break;
			case 'textbox':
				if(type=='datetime'){
					tmpl = '<textbox name="datetime'+random+'" width="" type="datetime" default="" readyonly="readyonly">请选择时间...</textbox>';
				}else{
					tmpl = '<textbox name="string'+random+'" width="" type="string" default="">请输入...</textbox>';
				}
				break;
			case 'droplist':
				if(type=='checkbox'){
					tmpl = '<select name="droplist'+random+'" width="" default="" style="droplist" multi="true"><option value="">请选择</option><option value="1">选项1</option><option value="2">选项2</option></select>';
				}else{
					tmpl = '<select name="droplist'+random+'" width="" default="" style="droplist" multi="false"><option value="">请选择</option><option value="1">选项1</option><option value="2">选项2</option></select>';
				}
				break;
			case 'checkbox':
				tmpl = '<select name="checkbox'+random+'" width="" default="" style="checkbox"><option value="1">选项1</option><option value="2">选项2</option></select>';
				break;
			case 'radio':
				tmpl = '<select name="radio'+random+'" width="" default="" style="radio"><option value="1">选项1</option><option value="2">选项2</option></select>';
				break;
			case 'repeat':
				tmpl = '<repeat name="repeat'+random+'" min="" max="">这是重复域</repeat>';
				break;
			default:
				tmpl = '';
				break;
		}
		return tmpl;
	}
	
	/**
     * @name FormatXML#formatCode
     * @function
     * @desc 格式化xml删除无效代码。
     */
	var hasError = false;
	var formatCode = function(xml){
		var tmpl = '';
		hasError = false;
		if(semi.utils.isEmpty(xml))return '';
		$(xml).each(function(){
			if($(this).isTag('repeat')){
				tmpl += matRepeat($(this));
			}else if($(this).isTag('line')){
				tmpl += matLine($(this));
			}else if($(this).isTag('text')){
				tmpl += matText($(this));
			}else if($(this).isTag('textbox')){
				tmpl += matTextbox($(this));
			}else if($(this).isTag('select')){
				tmpl += matSelect($(this));
			}
		});
		
		if(hasError){
			$dialog.confirm({
				content: '有无效的xml代码',
				ok: function(){},
				cancel: true
			})
		}
		//检查重名，删除重复name节点
		/*var nameArr = [],
			checkLine = function(node){
				node.children().each(function(){
					var name = $(this).attr('name');
					if(semi.utils.isEmpty(name))return true;
					if(nameArr.indexOf(name)==-1){
						nameArr.push(name);
					}else{
						$(this).remove();
					}
				});
			}, 
			_tmpl = '';
		
		$(tmpl).each(function(){
			if($(this).hasClass('alg_line')){
				checkLine($(this));
			}else if($(this).hasClass('alg_repeat')){
				$(this).children().each(function(){
					if($(this).hasClass('alg_line'))checkLine($(this));
				});
			}
			_tmpl += $(this)[0].outerHTML
		});*/
		/*tmpl = tmpl.replaceAll('><line', '>\n	<line')
					.replaceAll('<line><', '<line>\n	<')
					.replaceAll('></line>', '>\n</line>')*/
		tmpl = tmpl.replaceAll('><text>', '>\n<text>')
					.replaceAll('><text ', '>\n<text ')
					.replaceAll('><textbox', '>\n<textbox')
					.replaceAll('><select', '>\n<select');
		
		return tmpl;
	}
	var matRepeat = function(node){
		/*repeat元素的子元素是line
		name代表repeat元素的变量名
		min代表最少多少line
		max代表最大多少line*/
		var tmpl = '',
			name = node.attr('name') || '',
			min = parseInt(node.attr('min')) || 0,
			max = parseInt(node.attr('max')) || 100;
		
		if(semi.utils.isEmpty(name))return '';
		
		if(node.find('repeat').size()>0)hasError = true;
		
		if(node.find('repeat').remove().end().children().size()<1){
			tmpl = node.text();
			return node[0].outerHTML;
		}else{
			node.find('repeat').remove().end().children().each(function(){
				if($(this).isTag('line')){
					tmpl += matLine($(this));
				}else if($(this).isTag('text')){
					tmpl += matText($(this));
				}else if($(this).isTag('textbox')){
					tmpl += matTextbox($(this));
				}else if($(this).isTag('select')){
					tmpl += matSelect($(this));
				}
			});
		}
		tmpl = tmpl.replaceAll('><line', '>\n	<line')
					.replaceAll('</line>', '	</line>')
					.replaceAll('	<text>', '		<text>')
					.replaceAll('	<text ', '		<text ')
					.replaceAll('	<textbox', '		<textbox')
					.replaceAll('	<select', '		<select')
					.replaceAll('><text>', '>\n	<text>')
					.replaceAll('><text ', '>\n	<text ')
		   			.replaceAll('><textbox', '>\n	<textbox')
	   				.replaceAll('><select', '>\n	<select');
		
		return '<repeat name="'+name+'" min="'+min+'" max="'+max+'">\n	'+tmpl+'\n</repeat>';
	}
	var matLine = function(node){
		/*模板的核心元素是line，每一个line代表UI上的一行*/
		var tmpl = '';
		
		if(node.find('line').size()>0)hasError = true;
		
		if(node.find('line').remove().end().children().size()<1){
			return node[0].outerHTML;
		}else{
			node.find('line').remove().end().children().each(function(){
				if($(this).isTag('text')){
					tmpl += matText($(this));
				}else if($(this).isTag('textbox')){
					tmpl += matTextbox($(this));
				}else if($(this).isTag('select')){
					tmpl += matSelect($(this));
				}
			});
		}
		
		tmpl = tmpl.replaceAll('><text>', '>\n	<text>')
					.replaceAll('><text ', '>\n	<text ')
		   			.replaceAll('><textbox', '>\n	<textbox')
	   				.replaceAll('><select', '>\n	<select');
		return '<line>\n	'+tmpl+'\n</line>';
	}
	var matText = function(node){
		/*text元素：代表一段文字
		width: 宽度
		align: left, center, right 对齐方式
		bold: true, false 表示是否粗体*/
		var tmpl = '',
			text = node.text() || '',
			width = parseInt(node.attr('width')) || 'auto',
			align = node.attr('align') || '',
			bold = node.attr('bold') || 'false';
		
		return node[0].outerHTML;
	}
	var matTextbox = function(node){
		/*textbox元素：一个文字输入框
		name: 对应的变量名
		width: 宽度
		type: 变量类型。支持 number, string, datetime 3种类型
		default: 默认值，类型必须和type一致*/
		var tmpl = '<input class="form-control alg_ipt block" type="text" name="" value="{value}"/>',
			name = node.attr('name') || '',
			width = parseInt(node.attr('width')) || 130,
			type = node.attr('type') || 'string',
			def = node.attr('default') || '',
			placeholder = node.text() || '请输入';
		
		if(semi.utils.isEmpty(name))return '';
		return node[0].outerHTML;
	}
	var matSelect = function(node){
		/*select元素：选择输入
		multi: 是否多选
		name: 变量名
		width: 宽度
		type: 变量类型
		default: 默认值。如果是多选，值用逗号分割
		style: 显示的风格。droplist, checkbox, radio*/
		
		var tmpl = '', 
			option = '',
			name = node.attr('name') || '',
			multi = node.attr('multi') || 'false',
			width = parseInt(node.attr('width')) || 'auto',
			def = node.attr('default') || '-1',
			style = node.attr('style') || 'droplist';
		
		if(semi.utils.isEmpty(name))return '';
		return node[0].outerHTML;
	}
	
	return{
		gethtml: getHtml,
		getjson: getJson,
		gettmpl: getTemplete,
		inithtml: initHtml,
		initjson: initJson,
		format: formatCode
	}
	
});